<?php
// +----------------------------------------------------------------------
// | XShop小程序商城
// +----------------------------------------------------------------------
// | Author: Peak Xin <xinyflove@gmail.com>
// +----------------------------------------------------------------------

namespace app\api\model;

use think\Model;

class Product extends BaseModel {

    protected $hidden = ['delete_time', 'pivot', 'from', 'category_id', 'create_time', 'update_time'];

    /**
     * 读取器-处理表中main_img_url字段获取值
     * @param $val
     * @param $data
     * @return string
     */
    public function getMainImgUrlAttr($val, $data)
    {
        return $this->_prefixImgUrl($val, $data);
    }

    public function imgs()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

    public function properties()
    {
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    /**
     * 获取最新产品列表
     * @param $count
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getMostRecent($count)
    {
        $products = self::limit($count)->order('create_time desc')->select();
        return $products;
    }

    /**
     * 通过类目ID获取产品列表
     * @param $category_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function getProductsByCategoryId($category_id)
    {
        $products = self::where('category_id','=',$category_id)->select();
        return $products;
    }

    /**
     * 获取产品详情
     * @param $id
     * @return array|false|\PDOStatement|string|Model
     */
    public static function getProductDetail($id)
    {
        $product = self::with(['imgs'=>function($query){
            $query->with(['imgUrl'])->order('order', 'asc');
        }])->with(['properties'])->find($id);

        return $product;
    }
}
